using BasicData.API.Application.Command;
using BasicData.Domain.Entities;
using BasicData.ErrorCode;
using BasicData.Infrastructure.Interfasce;
using MediatR;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using System;
using System.Threading;
using System.Threading.Tasks;

namespace BasicData.API.Application.CommandHandlers
{
    /// <summary>
    /// 单个产品信息物理删除命令处理器
    /// </summary>
    public class SoftDeleteProductionCommandHandler : IRequestHandler<SoftDeleteProductionCommand, APIResult<bool>>
    {
        private readonly IBaseRepositroy<ProductionInfo> _productionInfoRepository;
        private readonly ILogger<SoftDeleteProductionCommandHandler> _logger;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="productionInfoRepository">产品信息仓储</param>
        /// <param name="logger">日志</param>
        public SoftDeleteProductionCommandHandler(
            IBaseRepositroy<ProductionInfo> productionInfoRepository,
            ILogger<SoftDeleteProductionCommandHandler> logger)
        {
            _productionInfoRepository = productionInfoRepository;
            _logger = logger;
        }

        /// <summary>
        /// 处理单个产品信息物理删除命令
        /// </summary>
        /// <param name="request">命令请求</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>操作结果</returns>
        public async Task<APIResult<bool>> Handle(SoftDeleteProductionCommand request, CancellationToken cancellationToken)
        {
            using (var tran= _productionInfoRepository.Db.Database.BeginTransaction())
            {
                try
                {
                    _logger.LogInformation("开始物理删除产品信息，ID：{Id}", request.ProductionId);

                    // 查找产品信息
                    var productionInfo = await _productionInfoRepository.GetByIdAsync(request.ProductionId)
                        .FirstOrDefaultAsync(p => !p.IsDeleted, cancellationToken);

                    if (productionInfo == null)
                    {
                        _logger.LogWarning("要删除的产品信息不存在或已删除，ID：{Id}", request.ProductionId);
                        return new APIResult<bool>
                        {
                            Code = ResultCode.删除失败,
                            Message = $"要删除的产品信息不存在或已删除，ID：{request.ProductionId}",
                            Data = false
                        };
                    }

                    // 执行物理删除
                    await _productionInfoRepository.DeleteAsync(productionInfo);
                    tran.Commit();
                    _logger.LogInformation("成功物理删除产品信息，ID：{Id}", request.ProductionId);
                    return new APIResult<bool>
                    {
                        Code = ResultCode.删除成功,
                        Message = "成功删除产品信息",
                        Data = true
                    };
                }
                catch (Exception ex)
                {
                    tran.Rollback();
                    _logger.LogError(ex, "物理删除产品信息时发生错误，ID：{Id}", request.ProductionId);
                    return new APIResult<bool>
                    {
                        Code = ResultCode.删除失败,
                        Message = $"物理删除产品信息失败: {ex.Message}",
                        Data = false
                    };
                }
            }
               
        }
    }
} 